package com.heima.behavior.service.impl;

import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.service.IUnlikeService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UnlikeServiceImpl implements IUnlikeService {


    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 不喜欢记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveUnLike(UnLikesBehaviorDto dto) {
        //构建 ApUnlikesBehavior
        ApUnlikesBehavior behavior = new ApUnlikesBehavior();
        User user = AppThreadLocalUtil.get();
        if (user != null) {
            behavior.setUserId(user.getUserId());
        } else {
            behavior.setEquipmentId(dto.getEquipmentId());
        }
        behavior.setArticleId(dto.getArticleId());
        behavior.setType(dto.getType());
        behavior.setCreatedTime(new Date());
        //查询历史记录
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (user == null) {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        } else {
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        }
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        //如果记录不存在 新增
        if (one == null){
            if (dto.getType() == 0){
                mongoTemplate.save(behavior);
            }
        }else {
            //记录存在 判断type是否一致
            //不一致的话进行更新
            if (one.getType() != dto.getType()){
                one.setType(dto.getType());
                mongoTemplate.save(one);
            }

        }
        return ResponseResult.okResult();
    }

    /**
     * 查询不喜欢记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<ApUnlikesBehavior> getUnlikes(UnLikesBehaviorDto dto) {
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (dto.getUserId() == null) {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        } else {
            query.addCriteria(Criteria.where("userId").is(dto.getUserId()));
        }
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        return ResponseResult.okResult(one);
    }
}
